package com.chwn.curiousdiary.ui.main.fragment;

import android.content.DialogInterface;
import android.content.Intent;
import android.content.pm.PackageInfo;
import android.content.pm.PackageManager;
import android.support.v7.app.AlertDialog;
import android.text.TextUtils;
import android.view.View;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ProgressBar;
import android.widget.TextView;

import com.chwn.curiousdiary.DiaryApplication;
import com.chwn.curiousdiary.R;
import com.chwn.curiousdiary.api.ISystemApi;
import com.chwn.curiousdiary.api.NetWork;
import com.chwn.curiousdiary.bean.MineNumBean;
import com.chwn.curiousdiary.bean.VersionBean;
import com.chwn.curiousdiary.gloable.Constant;
import com.chwn.curiousdiary.gloable.User;
import com.chwn.curiousdiary.gloable.UserUtils;
import com.chwn.curiousdiary.provider.DownloadStoryStore;
import com.chwn.curiousdiary.ui.login.LoginActivity;
import com.chwn.curiousdiary.ui.main.contract.MineContract;
import com.chwn.curiousdiary.ui.main.presenter.MinePresenter;
import com.chwn.curiousdiary.ui.other.FeedBackActivity;
import com.chwn.curiousdiary.ui.user.activity.CollectionActivity;
import com.chwn.curiousdiary.ui.user.activity.DownLoadActivity;
import com.chwn.curiousdiary.ui.user.activity.MessageActivity;
import com.chwn.curiousdiary.utils.FileUtils;
import com.chwn.curiousdiary.utils.ImgLoadUtil;
import com.chwn.curiousdiary.utils.UpdateAppUtils;
import com.chwn.harulib.mvp.base.BaseMVPFragment;
import com.chwn.harulib.mvp.rx.HttpResult;
import com.chwn.harulib.mvp.rx.RxSchedulers;
import com.chwn.harulib.util.NetUtils;
import com.umeng.analytics.MobclickAgent;

import java.util.HashMap;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;
import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.functions.Action0;
import rx.functions.Action1;
import rx.schedulers.Schedulers;


/**
 * Created by Myshikin on 2017/3/20.
 */

public class MineFragment extends BaseMVPFragment<MinePresenter> implements MineContract.View, View.OnClickListener {

    @BindView(R.id.user_head)
    ImageView    mUserHead;
    @BindView(R.id.iv_user_level)
    ImageView    mUserlevel;
    @BindView(R.id.tv_username)
    TextView     mUsernameTV;
    @BindView(R.id.tv_userphone)
    TextView     mUserphoneTV;
    @BindView(R.id.tv_login_out)
    TextView     mLoginOutTV;
    @BindView(R.id.tv_cache_size)
    TextView     mCacheSizeTV;
    @BindView(R.id.tv_last_version)
    TextView     mLastVersionTV;
    @BindView(R.id.ll_login_out)
    LinearLayout mLoginOut;
    @BindView(R.id.progressBar_cache)
    ProgressBar  mPBCache;
    @BindView(R.id.tv_coin_count)
    TextView     mCoinCount;
    @BindView(R.id.tv_collect_count)
    TextView     mCollectCount;
    @BindView(R.id.tv_down_count)
    TextView     mDownCount;
    @BindView(R.id.tv_message_count)
    TextView     mMessageCount;
    @BindView(R.id.tv_my_message)
    TextView     mMyMessage;
    @BindView(R.id.tv_feed_back)
    TextView     mFeedBack;
    @BindView(R.id.tv_update)
    TextView     mUpdate;
    @BindView(R.id.tv_history_count)
    TextView     mHistoryCount;
    @BindView(R.id.iv_unread_mark)
    ImageView    mUnreadMark;
    private DownloadStoryStore downFileStore;

    private int ids[] = new int[]{R.drawable.icon_l1, R.drawable.icon_l2, R.drawable.icon_l3
            , R.drawable.icon_l4, R.drawable.icon_l5, R.drawable.icon_l6
            , R.drawable.icon_l7, R.drawable.icon_l8, R.drawable.icon_l9, R.drawable.icon_l10,};


    @Override
    protected int setContentViewId() {
        return R.layout.fragment_mine;

    }

    @Override
    protected void initContentView() {
        ButterKnife.bind(this, mInflateContentView);

    }

    @Override
    protected void getData() {
        showContentView();
        mPresenter.getMyInfo();
    }

    @Override
    public void onStart() {
        super.onStart();
    }

    @Override
    public void onResume() {
        super.onResume();
        initViewData();
        mPresenter.getMyInfo();
    }

    @Override
    public void showMyInfo(MineNumBean bean) {
        mCollectCount.setText(bean.getStroyCollectedCount() + "");
        int unreadMessageCount = bean.getUnreadMessageCount();
        mMessageCount.setText(bean.getAllMessageCount() + "");
        mCoinCount.setText(bean.getCuriosityCount() + "");
        //        mUnreadMark.setVisibility(unreadMessageCount > 0 ? View.VISIBLE : View.GONE);
        mHistoryCount.setText(bean.getHistoryListenCount() + "");

        User user = DiaryApplication.mInstance.getmUser();
        if (user != null && user.getUserToken() != null) {
            String coinCount = user.getCoinCount();
        }
    }

    void initViewData() {
        updateCache();

        User user = DiaryApplication.mInstance.getmUser();
        if (user != null && user.getUserToken() != null) {
            //            mUsernameTV.setText(TextUtils.isEmpty(user.getNickName()) ? "好奇宝宝" : user.getNickName());

            mUsernameTV.setText("好奇宝宝");

            String level = user.getUserLevel();
            if (!TextUtils.isEmpty(level)) {
                int i = Integer.parseInt(level.split("\\.")[1]);
                if (i == 0) {
                    mUserlevel.setVisibility(View.GONE);
                } else {
                    mUserlevel.setVisibility(View.VISIBLE);
                    mUserlevel.setImageResource(ids[i - 1]);
                }
            } else {
                mUserlevel.setVisibility(View.GONE);
            }

            String phone = user.getPhone();
            if (!TextUtils.isEmpty(phone)) {
                String hindPhone = phone.substring(0, 3) + "****" + phone.substring(7);
                mUserphoneTV.setText("手机号：" + hindPhone);
            }
            mLoginOutTV.setText("退出登录");
            mLoginOut.setVisibility(View.VISIBLE);
            ImgLoadUtil.displayCircle(mUserHead, "", "0".equals(user.getBabysex()) ? R.drawable.icon_girl : R.drawable.icon_boy);
            if (downFileStore == null) {
                downFileStore = DownloadStoryStore.getInstance(mActivity);
            }
            int downLoadedCount = downFileStore.getDownLoadedCount();
            mDownCount.setText(downLoadedCount + "");
        } else {
            mUsernameTV.setText("未登录");
            mLoginOut.setVisibility(View.GONE);
            mUserlevel.setVisibility(View.GONE);
        }

        VersionBean versionBean = DiaryApplication.mInstance.versionBean;
        if (versionBean != null && versionBean.getUpdateVersionCode() > DiaryApplication.mInstance.currentVersionCode) {
            //最新版本
            mLastVersionTV.setText("V" + versionBean.getUpdateVersionName());
        } else if (versionBean != null && versionBean.getUpdateVersionCode() == DiaryApplication.mInstance.currentVersionCode) {
            //当前已是最新版本
            mLastVersionTV.setText("");
        }


    }

    private void updateCache() {
        Observable.create(new Observable.OnSubscribe<String>() {
            @Override
            public void call(Subscriber<? super String> subscriber) {
                String cacheFileSize = FileUtils.getCacheFileSize();
                subscriber.onNext(cacheFileSize);
            }
        }).subscribeOn(Schedulers.computation())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        mPBCache.setVisibility(View.VISIBLE);
                        mCacheSizeTV.setVisibility(View.GONE);
                    }
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<String>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        setCacheText("0.0M");
                    }

                    @Override
                    public void onNext(String str) {
                        setCacheText(str);
                    }
                });
    }


    @OnClick({R.id.ll_message, R.id.ll_commend_back,
            R.id.ll_history,
            R.id.ll_login_out, R.id.ll_my_collection,
            R.id.ll_my_download, R.id.ll_clear_cache, R.id.ll_update})
    public void onClick(View view) {
        HashMap<String, String> map;
        switch (view.getId()) {
            case R.id.ll_message:

                if (!UserUtils.isLogin(this)) {
                    return;
                }
                // user_enter_second_page_count
                map = new HashMap<>();
                map.put("type", "我的消息");
                MobclickAgent.onEvent(getContext(), "user_enter_second_page_count", map);

                startActivity(new Intent(mActivity, MessageActivity.class));
                break;
            case R.id.ll_history:
                if (!UserUtils.isLogin(this)) {
                    return;
                }
                // user_enter_second_page_count
                map = new HashMap<>();
                map.put("type", "历史记录");
                MobclickAgent.onEvent(getContext(), "user_enter_second_page_count", map);

                Intent intent = new Intent(mActivity, CollectionActivity.class);
                intent.putExtra(Constant.IS_HISTORY_PAGE, true);
                startActivity(intent);
                break;
            case R.id.ll_commend_back:
                map = new HashMap<>();
                map.put("type", "意见反馈");
                MobclickAgent.onEvent(getContext(), "user_enter_second_page_count", map);
                startActivity(new Intent(mActivity, FeedBackActivity.class));
                break;
            case R.id.ll_login_out:
                loginOut();
                break;
            case R.id.ll_my_collection:
                if (!UserUtils.isLogin(this)) {
                    return;
                }
                map = new HashMap<>();
                map.put("type", "我的收藏");
                MobclickAgent.onEvent(getContext(), "user_enter_second_page_count", map);
                startActivity(new Intent(mActivity, CollectionActivity.class));
                break;
            case R.id.ll_my_download:
                if (!UserUtils.isLogin(this)) {
                    return;
                }
                map = new HashMap<>();
                map.put("type", "我的下载");
                MobclickAgent.onEvent(getContext(), "user_enter_second_page_count", map);
                startActivity(new Intent(mActivity, DownLoadActivity.class));
                break;
            case R.id.ll_clear_cache:
                if (!"0.0M".equals(mCacheSizeTV.getText().toString())) {
                    clearAppCache();
                }
                //                clearDB();
                break;
            case R.id.ll_update:
                initVersionCode();
                initLastVersionCode();
                break;
        }
    }

    int currentVersionCode;

    void initVersionCode() {
        PackageManager pm = getContext().getPackageManager();//context为当前Activity上下文
        PackageInfo pi = null;
        try {
            pi = pm.getPackageInfo(getContext().getPackageName(), 0);
            currentVersionCode = pi.versionCode;
        } catch (PackageManager.NameNotFoundException e) {
            e.printStackTrace();
        }
    }


    private void initLastVersionCode() {

        if (!NetUtils.isNetWorkConnectted(getContext())) {
            return;
        }
        NetWork.getInstance()
                .getApiService(ISystemApi.class)
                .updateVersion(1, currentVersionCode)
                .compose(RxSchedulers.<HttpResult<VersionBean>>io_main())
                .subscribe(new Action1<HttpResult<VersionBean>>() {
                    @Override
                    public void call(HttpResult<VersionBean> versionBeanHttpResult) {
                        updataAPP(versionBeanHttpResult.getResdata());
                    }
                }, new Action1<Throwable>() {
                    @Override
                    public void call(Throwable throwable) {

                    }
                });
    }

    private void clearAppCache() {

        Observable.create(new Observable.OnSubscribe<Boolean>() {
            @Override
            public void call(Subscriber<? super Boolean> subscriber) {
                boolean b = FileUtils.clearAppCache();

                try {
                    Thread.sleep(3000);
                } catch (InterruptedException e) {
                    e.printStackTrace();
                }

                subscriber.onNext(b);
            }
        }).subscribeOn(Schedulers.io())
                .doOnSubscribe(new Action0() {
                    @Override
                    public void call() {
                        mPBCache.setVisibility(View.VISIBLE);
                        mCacheSizeTV.setVisibility(View.GONE);
                    }
                }).subscribeOn(AndroidSchedulers.mainThread())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Subscriber<Boolean>() {
                    @Override
                    public void onCompleted() {

                    }

                    @Override
                    public void onError(Throwable e) {
                        setCacheText("0.0M");
                    }

                    @Override
                    public void onNext(Boolean aBoolean) {
                        setCacheText("0.0M");
                    }
                });
    }

    private void setCacheText(String cache) {
        mPBCache.setVisibility(View.GONE);
        mCacheSizeTV.setVisibility(View.VISIBLE);
        mCacheSizeTV.setText(cache);
    }


    private void show() {
        AlertDialog.Builder builder = new AlertDialog.Builder(getActivity());
        builder.setTitle("退出登录");
        builder.setNegativeButton("取消", null);
        builder.setPositiveButton("确定", new DialogInterface.OnClickListener() {
            @Override
            public void onClick(DialogInterface dialogInterface, int i) {
                DiaryApplication.mInstance.loginOut();
                Intent intent = new Intent(getActivity(), LoginActivity.class);
                startActivity(intent);
                getActivity().finish();
            }
        });
        builder.show();
    }

    private void loginOut() {
        if (DiaryApplication.mInstance.isLogin()) {
            show();
        } else {
            Intent intent = new Intent(getActivity(), LoginActivity.class);
            startActivity(intent);
        }
    }

    private void updataAPP(final VersionBean version) {
        UpdateAppUtils.updataAPP(version, getActivity());
    }
}
